package cn.zhl.algorithm._3_并查集.impl;

/**
 * @program: demos
 * @description: 基于高度的优化，合并的时候查看两边的根节点下面子元素的高度
 * @author: 刘振华
 * @create: 2020-06-11 19:00
 **/
public class QuickUnionHeight extends QuickUnion {
	private int[] heights;
	public QuickUnionHeight(int capacity){
		super(capacity);
		heights = new int[capacity];
		for(int i = 0;i<capacity;i++){
			heights[i] = 1;
		}
	}
	@Override
	public int union(int v1, int v2) {
		int oldRoot = find(v1);
		int newRoot = find(v2);
		if(oldRoot == newRoot){
			return oldRoot;
		}
		if(heights[oldRoot]< heights[newRoot]){
			parent[oldRoot] = newRoot;
			return newRoot;
		}else if(heights[oldRoot]> heights[newRoot]){
			parent[newRoot] = oldRoot;
			return oldRoot;
		}else {
			parent[oldRoot] = newRoot;
			heights[newRoot] += 1;
			return newRoot;
		}
	}
}
